/*
 * @Author: your name
 * @Date: 2021-03-04 17:38:08
 * @LastEditTime: 2021-03-04 19:23:14
 * @LastEditors: Please set LastEditors
 * @Description: 将数组元素向右移动K个位置，K>=0，改变原数组
 * @FilePath: \relearnJS\interview\array\旋转数组.js
 */
var arr = [1, 2, 3, 4, 5, 6],
    k = 7
//? 1. 临时数组
let tmp = [...arr],
    len = arr.length
k %= len
for (var i = 0; i < len; i++) {
    arr[(i + k) % len] = tmp[i]
}
console.log('临时数组：', arr)

//? 2. 部分元素多次翻转
arr = [1, 2, 3, 4, 5, 6]

function myReverse(arr, start, end) {
    while (start < end) {
        var tmp = arr[start]
        arr[start++] = arr[end]
        arr[end--] = tmp
    }
}
// 整体翻转
myReverse(arr, 0, len - 1)
// 前部分翻转
myReverse(arr, 0, k - 1)
// 后部分翻转
myReverse(arr, k, len - 1)
console.log('部分翻转：', arr)

//? 3. 环形旋转
arr = [1, 2, 3, 4, 5, 6]
var visited = new Map(),
    hold = arr[0],
    index = 0
for (var i = 0; i < len; i++) {
    index = (index + k) % len
    if (!visited.has(index)) {
        visited.set(index, 0)
        var t = arr[index]
        arr[index] = hold
        hold = t
    } else {
        index = (index + 1) % len
        hold = arr[index]
        i--
    }
    console.log(index, hold)
}
console.log('环形旋转：', arr)